package com.weixing.mall.provider.auth.member.openid;

import com.weixing.oauth2.common.handler.RestFulAuthenticationFailureHandler;
import com.weixing.oauth2.common.handler.RestFulAuthenticationSuccessHandler;
import com.weixing.oauth2.common.userdetails.IUserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @ClassName SysUserUserNameAndPasswordLoginConfig
 * @Description  后台管理员：用户名密码登陆配置
 * @Author Small
 * @Date 2019/12/30 10:18
 * @Version 1.0
 **/
@Component
public class MemberOpenIdLoginConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private RestFulAuthenticationSuccessHandler restFulAuthenticationSuccessHandler;
    @Autowired
    private RestFulAuthenticationFailureHandler restFulAuthenticationFailureHandler;
    @Autowired
    @Qualifier("memberAuthService")
    private IUserAuthService memberAuthService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(HttpSecurity http)  {
//        restFulAuthenticationSuccessHandler.setUserAuthService(memberAuthService);
        // 此处采用new的方式，而不是@Component和@Autowired结合，目的为了方便安装和卸载，可重用可移植性强
        MemberOpenIdAuthenticationFilter authenticationFilter = new MemberOpenIdAuthenticationFilter();
        authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        authenticationFilter.setAuthenticationSuccessHandler(restFulAuthenticationSuccessHandler);
        authenticationFilter.setAuthenticationFailureHandler(restFulAuthenticationFailureHandler);
        http.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // 设置自定义provider
        MemberOpenIdAuthenticationProvider provider = new MemberOpenIdAuthenticationProvider();
        provider.setUserDetailService(memberAuthService);
        provider.setPasswordEncoder(passwordEncoder);
        http.authenticationProvider(provider);
    }
}
